﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Communicator;
using System.Threading;

namespace TestCommunicator
{
    public partial class FormClient : Form
    {
        public FormClient()
        {
            InitializeComponent();
        }

        private Client client = new Client();

        private void btnConnect_Click(object sender, EventArgs e)
        {
            client.FpConnected = (x, y) => { AppendLog("Connected to " + ((Client)x).ServerIP + ":" + ((Client)x).ServerPort); };
            client.FpDisconnected = (x, y) => { AppendLog("Disconnected from " + ((Client)x).ServerIP + ":" + ((Client)x).ServerPort); };
            client.FpSend = (x, y) => { AppendLog("Sent: '" + y + "' to Server !"); };
            client.FpRecv = (x, y) => { AppendLog("Recv: '" + y + "' from Server !"); };

            client.ServerIP = txtIPAddress.Text;
            client.ServerPort = int.Parse(txtPort.Text);
            client.Connect();
        }

        private void AppendLog(string mess)
        {
            string msg = string.Format("[{0}] {1}\n", DateTime.Now, mess);
            Invoke(new ThreadStart(() =>
                {
                    txtLog.AppendText(msg);
                }));
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (client.Connected)
            {
                string msg = txtMsgContent.Text;
                client.Send(msg);
            }
            else
                MessageBox.Show("Chưa kết nối đến server !");
        }
    }
}
